#include "ohos_display_manager.h"
#include "rtc_base/logging.h"

namespace webrtc {

void DisplayChangeCallback(uint64_t displayId) {
	RTC_LOG(LS_INFO) << "DisplayChangeCallback displayId=" << displayId;
	NativeDisplayManager_ErrorCode errCode;

	NativeDisplayManager_Orientation displayOrientation;
	if (OH_NativeDisplayManager_GetDefaultDisplayOrientation(&displayOrientation) == NativeDisplayManager_ErrorCode::DISPLAY_MANAGER_OK) {
		DisplayManagerOhos::GetInstance()->SetDefaultDisplayOrientation(displayOrientation);
	}

	NativeDisplayManager_Rotation displayRotation;
	if (OH_NativeDisplayManager_GetDefaultDisplayRotation(&displayRotation) == NativeDisplayManager_ErrorCode::DISPLAY_MANAGER_OK) {
		DisplayManagerOhos::GetInstance()->SetDefaultDisplayRotation(displayRotation);
	} 
}

std::shared_ptr<DisplayManagerOhos> DisplayManagerOhos::GetInstance() {
	static auto inst = new std::shared_ptr<DisplayManagerOhos>(new DisplayManagerOhos());
	return *inst;
}

void DisplayManagerOhos::Init() {
	static std::once_flag initFlag;    
	std::call_once(initFlag, [&]() {
		listener_index = 0;
		NativeDisplayManager_ErrorCode errCode = OH_NativeDisplayManager_RegisterDisplayChangeListener(DisplayChangeCallback, &listener_index);
		if (errCode != NativeDisplayManager_ErrorCode::DISPLAY_MANAGER_OK) {
			RTC_LOG(LS_ERROR) << "DisplayManagerOhos::Init RegisterDisplayChangeListener error index: " << listener_index << " errCode: " << errCode;
		} else {
			RTC_LOG(LS_INFO) << "DisplayManagerOhos::Init RegisterDisplayChangeListener index: " << listener_index;
		} 
		OH_NativeDisplayManager_GetDefaultDisplayOrientation(&default_display_orientation_);
		OH_NativeDisplayManager_GetDefaultDisplayRotation(&default_display_rotation_);
		RTC_LOG(LS_INFO) << "DisplayManagerOhos::Init orientation:" << default_display_orientation_ << " rotation:" << default_display_rotation_;
		inited_ = true;
	});
}


DisplayManagerOhos::DisplayManagerOhos() {
	RTC_LOG_T(LS_INFO) << "DisplayManagerOhos ctor";
}

DisplayManagerOhos::~DisplayManagerOhos() {
	RTC_LOG_T(LS_INFO) << "DisplayManagerOhos dtor";
	if (inited_) {
		RTC_LOG(LS_INFO) << "DisplayManagerOhos UnRegisterDisplayChangeListener index: " << listener_index;
		OH_NativeDisplayManager_UnregisterDisplayChangeListener(listener_index);
	}
}


void DisplayManagerOhos::SetDefaultDisplayOrientation(NativeDisplayManager_Orientation orientation) {
	RTC_LOG_T(LS_INFO) << "DisplayManagerOhos::SetDefaultDisplayOrientation orientation=" << orientation;
	default_display_orientation_ = orientation;
}

void DisplayManagerOhos::SetDefaultDisplayRotation(NativeDisplayManager_Rotation rotation) {
	RTC_LOG_T(LS_INFO) << "DisplayManagerOhos::SetDefaultDisplayRotation rotation=" << rotation;
	default_display_rotation_ = rotation;
}

}
